//
//  MeRegisterRegisterDefault.m
//  ZITHER
//
//  Created by weixin on 2019/1/16.
//  Copyright © 2019 weixn. All rights reserved.
//

#import "MeRegisterRegisterDefault.h"
#import "OKGetCodeBtn.h"
#import <UMPush/UMessage.h>
#import "MeRegisterSucceedVC.h"
#import "MyHelpCentreWebVC.h"
#import <TCWebCodesSDK/TCWebCodesBridge.h>

@interface MeRegisterRegisterDefault()<QMUITextFieldDelegate>

@property (nonatomic,strong)QMUITextField *userFt;
@property (nonatomic,strong)QMUITextField *codeFt;
@property (nonatomic,strong)QMUITextField *passwordFt;

@property (nonatomic,strong)BaseBtn *donebtn;
@property (nonatomic,strong)UIButton *eyebtn;
@property (nonatomic,strong)OKGetCodeBtn * codeBtn;

@property (nonatomic,strong)BaseLab *redTipe;//报错提示

@property (nonatomic,strong)BaseBtn *ExceptionClauseBtn;//免责条款
@property (nonatomic,strong)BaseLab *ExceptionClauseLab;//免责条款


@end

@implementation MeRegisterRegisterDefault

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUI];
        [self setMasonry];
    }
    return self;
}

-(void)setState:(MeRegisterRegisterState)state{
    _state = state;
    if (self.state == MeRegisterRegisterStateSetPassword) {
        self.userFt.text = kUSER_INFO_MANAGER.phone;
        self.userFt.enabled = NO;
    }
}

-(void)setUI{
    
    [self addSubview:self.userFt];
    [self addSubview:self.codeFt];
    [self addSubview:self.passwordFt];
    [self addSubview:self.donebtn];
    [self addSubview:self.codeBtn];
    [self addSubview:self.eyebtn];
    [self addSubview:self.ExceptionClauseBtn];
    [self addSubview:self.ExceptionClauseLab];
}

-(void)setMasonry{
    
    [self.userFt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(15);
        make.right.equalTo(self).offset(-15);
        make.height.mas_equalTo(40);
        make.top.equalTo(self).offset(80);
    }];
    
    [self.codeFt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(15);
        make.right.equalTo(self).offset(-15);
        make.height.mas_equalTo(40);
        make.top.equalTo(self.userFt.mas_bottom).offset(20);
    }];
    
    [self.passwordFt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(15);
        make.right.equalTo(self).offset(-15);
        make.height.mas_equalTo(40);
        make.top.equalTo(self.codeFt.mas_bottom).offset(20);
    }];
    
    [self.donebtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self).offset(15);
        make.right.equalTo(self).offset(-15);
        make.height.mas_equalTo(45);
        make.top.equalTo(self.passwordFt.mas_bottom).offset(50);
    }];
    
    [self.codeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.codeFt).offset(0);
        make.top.equalTo(self.codeFt).offset(0);
        make.height.width.mas_equalTo(36);
    }];
    
    BaseView *view = [[BaseView alloc]initWithFrame:CGRectMake(0, 0, 1, 16)];
    view.backgroundColor = HexColor(0x999999);
    [self addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.codeBtn.mas_centerY).offset(0);
        make.right.equalTo(self.codeBtn.mas_left).offset(-15);
        make.height.mas_equalTo(16);
        make.width.mas_equalTo(1);
    }];
    [self.eyebtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.passwordFt).offset(0);
        make.top.equalTo(self.passwordFt).offset(0);
        make.height.width.mas_equalTo(36);
    }];
    [self addSubview:self.redTipe];
    [self.redTipe mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.passwordFt.mas_bottom).offset(10);
        make.left.equalTo(self).offset(15);
    }];
    
    [self.ExceptionClauseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.donebtn.mas_bottom).offset(10);
        make.centerX.equalTo(self.mas_centerX).offset(+30);
    }];
    [self.ExceptionClauseLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.donebtn.mas_bottom).offset(10);
        make.centerX.equalTo(self.mas_centerX).offset(-30);
    }];
}


-(QMUITextField *)userFt{
    if (!_userFt) {
        _userFt = [[QMUITextField alloc]initWithFrame:CGRectMake(0, 100, 150, 50)];
        _userFt.font = [UIFont systemFontOfSize:25];
        _userFt.delegate = self;
        _userFt.placeholderColor = [UIColor whiteColor]; // 自定义 placeholder 的颜色
        _userFt.returnKeyType = UIReturnKeyDone;
        _userFt.enablesReturnKeyAutomatically = YES;
        _userFt.tintColor = [UIColor colorWithHex:@"333333"];
        // 限制可输入的字符长度
        //        _userFt.maximumTextLength = 11;
        _userFt.qmui_borderWidth = 1;
        _userFt.qmui_borderPosition = QMUIViewBorderPositionBottom;
        //        _userFt.keyboardType = UIKeyboardTypeNumberPad;
        _userFt.qmui_borderColor = [UIColor colorWithHex:@"eeeeee"];
        _userFt.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:15];
        
        
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        NSAttributedString *attri = [[NSAttributedString alloc] initWithString:@"输入手机号/邮箱" attributes:@{NSForegroundColorAttributeName:[UIColor colorWithHex:@"999999"],NSFontAttributeName:[UIFont fontWithName:@"PingFang-SC-Regular" size:15], NSParagraphStyleAttributeName:style}];
        _userFt.attributedPlaceholder = attri;
        
        
    }
    return _userFt;
}

-(QMUITextField *)passwordFt{
    if (!_passwordFt) {
        _passwordFt = [[QMUITextField alloc]initWithFrame:CGRectMake(0, 100, 150, 50)];
        _passwordFt.font = [UIFont systemFontOfSize:25];
        _passwordFt.delegate = self;
        _passwordFt.placeholderColor = [UIColor whiteColor]; // 自定义 placeholder 的颜色
        _passwordFt.returnKeyType = UIReturnKeyDone;
        _passwordFt.enablesReturnKeyAutomatically = YES;
        _passwordFt.tintColor = [UIColor colorWithHex:@"333333"];
        // 限制可输入的字符长度
        _passwordFt.maximumTextLength = 11;
        _passwordFt.qmui_borderWidth = 1;
        _passwordFt.qmui_borderPosition = QMUIViewBorderPositionBottom;
        //        _passwordFt.keyboardType = UIKeyboardTypeNumberPad;
        _passwordFt.qmui_borderColor = [UIColor colorWithHex:@"eeeeee"];
        _passwordFt.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:15];
        _passwordFt.secureTextEntry = YES;
        
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        NSAttributedString *attri = [[NSAttributedString alloc] initWithString:@"设置6-12位登录密码" attributes:@{NSForegroundColorAttributeName:[UIColor colorWithHex:@"999999"],NSFontAttributeName:[UIFont fontWithName:@"PingFang-SC-Regular" size:15], NSParagraphStyleAttributeName:style}];
        _passwordFt.attributedPlaceholder = attri;
        
        
    }
    return _passwordFt;
}

-(QMUITextField *)codeFt{
    if (!_codeFt) {
        _codeFt = [[QMUITextField alloc]initWithFrame:CGRectMake(0, 100, 150, 50)];
        _codeFt.font = [UIFont systemFontOfSize:25];
        _codeFt.delegate = self;
        _codeFt.placeholderColor = [UIColor whiteColor]; // 自定义 placeholder 的颜色
        _codeFt.returnKeyType = UIReturnKeyDone;
        _codeFt.enablesReturnKeyAutomatically = YES;
        _codeFt.tintColor = [UIColor colorWithHex:@"333333"];
        // 限制可输入的字符长度
        _codeFt.maximumTextLength = 4;
        _codeFt.qmui_borderWidth = 1;
        _codeFt.qmui_borderPosition = QMUIViewBorderPositionBottom;
        _codeFt.keyboardType = UIKeyboardTypeNumberPad;
        _codeFt.qmui_borderColor = [UIColor colorWithHex:@"eeeeee"];
        _codeFt.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:15];
//        _codeFt.secureTextEntry = YES;
        
//        if (@available(iOS 12.0, *)) {
//            //Xcode 10 适配
//            _codeFt.textContentType = UITextContentTypeOneTimeCode;
//            //非Xcode 10 适配
//            _codeFt.textContentType = @"one-time-code";
//        }
        
        
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        NSAttributedString *attri = [[NSAttributedString alloc] initWithString:@"输入验证码" attributes:@{NSForegroundColorAttributeName:[UIColor colorWithHex:@"999999"],NSFontAttributeName:[UIFont fontWithName:@"PingFang-SC-Regular" size:15], NSParagraphStyleAttributeName:style}];
        _codeFt.attributedPlaceholder = attri;

    }
    return _codeFt;
}


-(BaseBtn *)donebtn{
    if (!_donebtn) {
        _donebtn = [[BaseBtn alloc]initializeFrame:CGRectMake(0, 0, 0, 0) NormalText:@"确定" NormalTextColor:[UIColor whiteColor] SeleText:nil SeleTextColor:nil font:14 isBold:NO];
        _donebtn.backgroundColor = baseColorTheme;
        _donebtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:15];
        _donebtn.alpha = 0.5;
        _donebtn.enabled = NO;
        [_donebtn setCornerRadiusWithRadius:4 isMasks:YES];
        
        @weakify(self);
        [[_donebtn rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            
            if (self.passwordFt.text.length<6) {
                self.redTipe.hidden = NO;
                self.redTipe.text = @"密码不能少于6位";
                return ;
            }
            
            switch (self.state) {
                case MeRegisterRegisterStateRegister:
                    [self btnRegister];
                    break;
                case MeRegisterRegisterStateForget:
                    [self btnForget];
                    break;
                case MeRegisterRegisterStateSetPassword:
                    [self btnForget];
//                    [self btnPassword];//需求改了直接调用忘记密码
                    break;
                    
                default:
                    break;
            }
            
            

        }];
    }
    return _donebtn;
}

-(void)btnRegister{
    @weakify(self);
    [[AccountService loadLoginForregistry:self.userFt.text credential:self.codeFt.text password:self.passwordFt.text reponseObjctClass:nil]subscribeNext:^(ResponseData * x) {
        @strongify(self);

        if (x.success) {
            [kUSER_INFO_MANAGER saveCookie];
            ResponseData *data = x;
            UserInfoManager *model = [[UserInfoManager alloc]init];
            
            [model setUserInfoWithNSDictionary: data.responseRawData[@"data"]];
            
            model.token = [NSString stringWithFormat:@"Bearer %@",model.token];
            [kUSER_INFO_MANAGER setUserInfoWithModel:model];
            [kUSER_INFO_MANAGER MyList];
            //                UserInfoManager *mdoel = [UserInfoManager defaultManager];
            //                [self.navigationController pushViewController:[[MeVC alloc]init] animated:YES];
            //绑定别名
            [UMessage addAlias:model.userId type:@"userId" response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
                NSLog(@"");
            }];
            if (self.state == MeRegisterRegisterStateForget) {
                [self.getNav popToRootViewControllerAnimated:YES];
            }else{
                [self.getNav pushViewController:[[MeRegisterSucceedVC alloc]init] animated:YES];
            }
        
            
        }else{
            self.redTipe.hidden = NO;
            self.redTipe.text = x.errorInfo;
//            [Tools showTips:x.errorInfo];
        }
    }];
}

-(void)btnForget{
    @weakify(self);
    [[AccountService loadLoginForforget:self.userFt.text credential:self.codeFt.text password:self.passwordFt.text reponseObjctClass:nil]subscribeNext:^(ResponseData * x) {
        @strongify(self);
        
        if (x.success) {
            [self.getNav popToRootViewControllerAnimated:YES];
            [Tools showTips:@"修改密码成功"];
        }else{
            self.redTipe.hidden = NO;
            self.redTipe.text = x.errorInfo;
//            [Tools showTips:x.errorInfo];
        }
    }];
}

-(void)btnPassword{
  
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{

    self.redTipe.hidden = YES;

    NSString *toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    //明文切换密文后避免被清空
    if (textField == self.passwordFt ){
        if (![self isConformToSpecificationsForPassword:toBeString]) {
            return NO;
        }
    }
    
    if ( textField == self.userFt ) {
        //查看是否符合规范
        if (![self isConformToSpecifications:toBeString]) {
            return NO;
        }
    }

    if (textField == self.passwordFt && textField.isSecureTextEntry) {
        textField.text = toBeString;
        if (textField.text.length == 0) {
            NSLog(@"打开禁用");
            self.eyebtn.enabled = NO;
            self.eyebtn.userInteractionEnabled =NO;
            self.donebtn.enabled = NO;
            self.donebtn.alpha = 0.5;
        }else{
            NSLog(@"关闭禁用");
            self.eyebtn.enabled = YES;
            self.eyebtn.userInteractionEnabled =YES;
            self.donebtn.enabled = YES;
            self.donebtn.alpha = 1;
        }
        return NO;
    }
    return YES;
}

-(BOOL)isConformToSpecifications:(NSString*)string{
    NSUInteger lengthOfString = string.length;//lengthOfString的值始终为1
    for (NSInteger loopIndex = 0; loopIndex < lengthOfString; loopIndex++) {
        unichar character = [string characterAtIndex:loopIndex];//将输入的值转化为ASCII值（即内部索引值），可以参考ASCII表
        if (character == 64 ||character == 46) {
            return YES;
        }
         // 48-57;{0,9};65-90;{A..Z};97-122:{a..z}
        if (character < 48) return NO; // 48 unichar for 0
        
        if (character > 57 && character < 65) return NO; //
        
        if (character > 90 && character < 97) return NO;
        
        if (character > 122) return NO;
        
    }
    return YES;
}

-(BOOL)isConformToSpecificationsForPassword:(NSString*)string{
    NSUInteger lengthOfString = string.length;//lengthOfString的值始终为1
    for (NSInteger loopIndex = 0; loopIndex < lengthOfString; loopIndex++) {
        unichar character = [string characterAtIndex:loopIndex];//将输入的值转化为ASCII值（即内部索引值），可以参考ASCII表
//        if (character == 64 ||character == 46) {
//            return YES;
//        }
        // 48-57;{0,9};65-90;{A..Z};97-122:{a..z}
        if (character < 48) return NO; // 48 unichar for 0
        
        if (character > 57 && character < 65) return NO; //
        
        if (character > 90 && character < 97) return NO;
        
        if (character > 122) return NO;
        
    }
    return YES;
}


-(OKGetCodeBtn *)codeBtn{
    if (!_codeBtn) {
        _codeBtn = [[OKGetCodeBtn alloc]initWithFrame:CGRectMake(kScreenW-100, 0, 100, 40)];
        //        _codeBtn.backgroundColor = [UIColor redColor];
        _codeBtn.strTime= @"";
        [_codeBtn setTitle:@"获取" forState:UIControlStateNormal];
        
        _codeBtn.titleLabel.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:15];
        
        [_codeBtn setTitleColor:baseColorTheme forState:UIControlStateNormal];
        @weakify(self);
        [[_codeBtn rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            [self endEditing:YES];

            [[TCWebCodesBridge sharedBridge]loadTencentCaptcha:self appid:@"2097119585" callback:^(NSDictionary *resultJSON) {
                if(0==[resultJSON[@"ret"] intValue]) {
                    /**
                     验证成功
                     返回内容：
                     resultJSON[@"appid"]为回传的业务appid
                     resultJSON[@"ticket"]为验证码票据
                     resultJSON[@"randstr"]为随机串
                     */
                    NSLog(@"");

                    [[AccountService loadLoginForsendCode:self.userFt.text ticket:resultJSON[@"ticket"] randstr:resultJSON[@"randstr"] reponseObjctClass:nil]subscribeNext:^(ResponseData * x) {
                        @strongify(self);
                        
                        if (x.success) {
                            [self.codeBtn timeFailBeginFrom:45];
                            self.codeBtn.alpha = 0.4;
                            [self.codeBtn setTitle:@"45S" forState:UIControlStateNormal];
                            [self.codeBtn setTitleColor:[UIColor colorWithHex:@"999999"] forState:UIControlStateNormal];
                            [Tools showTips:@"发送验证码成功"];
                        }else{
                            self.redTipe.hidden = NO;
                            self.redTipe.text = x.errorInfo;
                        }
                        
                    }];
                } else {
                    /**
                     验证失败
                     返回内容：
                     ret=-1001为验证码js加载错误
                     ret=-1002一般为网络错误
                     ret=-1为返回票据数据解析错误，业务可根据需要重试处理
                     ret的其他返回值，为验证失败，比如用户主动关闭了验证码弹框
                     */
                    [Tools showTips:@"验证验证码校验失败"];

                }
            }];
            
       
        }];
        
    }
    return _codeBtn;
}


-(UIButton *)eyebtn{
    if (!_eyebtn) {
        //        _eyebtn = [[BaseBtn alloc]initializeFrame:CGRectMake(kScreenW-60, 0, 32, 32) NormalImage:@"登录_不可见" SeleImage:@"登录_可见"];
        
        _eyebtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _eyebtn.frame = CGRectMake(kScreenW-60, 0, 32, 32);
        _eyebtn.enabled = NO;
        _eyebtn.userInteractionEnabled =NO;
        [_eyebtn setImage:[UIImage imageNamed:@"登录_不可见"] forState:UIControlStateNormal];
        [_eyebtn setImage:[UIImage imageNamed:@"登录_可见"] forState:UIControlStateSelected];
        [_eyebtn setImage:[UIImage imageNamed:@"登录_可见（不可点击状态）"] forState:UIControlStateDisabled];
        
        
        //        _eyebtn.backgroundColor = [UIColor redColor];
        @weakify(self);//登录_可见（不可点击状态）
        [[_eyebtn rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            self.eyebtn.selected = !self.eyebtn.selected;
            self.passwordFt.secureTextEntry = !self.passwordFt.secureTextEntry;
        }];
    }
    return _eyebtn;
}

-(BaseLab *)redTipe{
    if (!_redTipe) {
        _redTipe = [[BaseLab alloc]initializeFrame:CGRectMake(0, 0, 1, 1) text:@"输入手机号错误" font:12 textColor:[UIColor colorWithHex:@"FF6F6F"] isBold:NO numberOfLines:0];
        _redTipe.font = [UIFont fontWithName:@"PingFangSC-Medium" size:12];
        _redTipe.hidden = YES;
    }
    return _redTipe;
}

-(BaseBtn *)ExceptionClauseBtn{
    if (!_ExceptionClauseBtn) {
        _ExceptionClauseBtn = [[BaseBtn alloc]initializeFrame:CGRectMake(0, 0, 0, 0) NormalText:@"《免责条款》" NormalTextColor:baseColorTheme SeleText:@"" SeleTextColor:[UIColor whiteColor] font:12 isBold:NO];
        _ExceptionClauseBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _ExceptionClauseBtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:12];

        /** 按钮点击案例 */
        @weakify(self);
        [[_ExceptionClauseBtn rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            
            MyHelpCentreWebVC *vc = [[MyHelpCentreWebVC alloc]init];
            
//            vc.url = [NSString stringWithFormat:@"%@/#/faq/clause",RootUrlWeb];
            NSString *urlString = [NSString stringWithFormat:@"%@/#/faq/clause?name=%@",RootUrlWeb,RootProjectName];

            NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)urlString,(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",NULL,kCFStringEncodingUTF8));
            
            vc.url = encodedString;

            vc.title1 = @"免责条款";
            
            [self.getNav pushViewController:vc animated:YES];
            
        }];
    }
    return _ExceptionClauseBtn;
}
-(BaseLab *)ExceptionClauseLab{
    if (!_ExceptionClauseLab) {
        _ExceptionClauseLab = [[BaseLab alloc]initializeFrame:CGRectMake(0, 0, 0, 0) text:@"注册即同意" font:11 textColor:HexColor(0x333333) isBold:NO numberOfLines:0];
        _ExceptionClauseLab.font = [UIFont fontWithName:@"PingFangSC-Medium" size:12];
        _ExceptionClauseLab.textAlignment = NSTextAlignmentRight;
    }
    return _ExceptionClauseLab;
}
@end
